package com.insurance.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.insurance.common.Contants;
import com.insurance.common.ResultData;
import com.insurance.pojo.PayInfo;
import com.insurance.pojo.Refund;
import com.insurance.pojo.Usearea;
import com.insurance.service.OrderPayService;
import com.insurance.utils.UuidUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: 李辽
 * Date: 2020/10/28 16:49
 * Description:订单支付信息
 * Version: V1.0
 */
@Api(value = "订单支付信息配置",tags = "订单支付信息相关配置API")
@Controller
public class OrderPayController {
    @Autowired
    private OrderPayService payService;
    /**+
     * 支付
     * @param payInfo
     * @param response
     * @param req
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/payOrder.do",method = RequestMethod.POST)
    @ApiOperation(value = "支付接口",notes = "支付接口",httpMethod = "post",response = ResultData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="支付成功"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ResponseBody
    public ResultData  payOrder(@RequestBody PayInfo payInfo, HttpServletResponse response, HttpServletRequest req) throws IOException {//获取数据方式待定
        ResultData resultData = new ResultData();
        // alipay测试支付地址
        String URL = "https://openapi.alipaydev.com/gateway.do";
        // 生产环境支付地址为https://openapi.alipay.com/gateway.do
        // 创建的应用ID
        String APP_ID = "2016103000779855";
        //自己的私钥
        String APP_PRIVATE_KEY = Contants.APP_PRIVATE_KEY;
        //支付宝的公钥
        String ALIPAY_PUBLIC_KEY = Contants.ALIPAY_PUBLIC_KEY;

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, "json", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2");
        //  创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 用户确认支付后，支付宝get请求returnUrl
        alipayRequest.setReturnUrl("http://172.16.10.111:8080/addpayOrder.do");
        /*/alipayRequest.setReturnUrl("http://172.16.10.189:8080/#/guanliHome/guanlipingjia");
        // 交易成功后，支付宝post请求notifyUrl（商户入参传入）

        /*
            由于同步返回的不可靠性，支付结果必须以异步通知或查询接口返回为准，不能依赖同步跳转。
            商户系统接收到异步通知以后，必须通过验签（验证通知中的sign参数）来确保支付通知是由支付宝发送的。
         */
        /*
             填充业务参数
                 out_trade_no   每笔订单号需要自身的唯一id，支付宝会根据此id判断是否交易
                 total_amount   这笔订单的价格
                 subject        订单商品名称
                 product_code   支付方式：QUICK_WAP_PAY 登录账号支付
             这四个参数应该从结算页面传递过来
         */
        System.out.println(payInfo);
        // 每笔订单号需要自身的唯一id，支付宝会根据此id判断是否交易
        String out_trade_no = payInfo.getOrderNumber();
        // 这笔订单的价格
        String total_amount = payInfo.getUserPayble();
        // 订单商品名称
        String subject = payInfo.getProductName();
        // 支付方式：QUICK_WAP_PAY 登录账号支付
        String product_code = "QUICK_WAP_PAY";
        String bizContent = "{" +
                "\"out_trade_no\":\"" + out_trade_no + "\"," +
                "\"total_amount\":" + total_amount + "," +
                "\"subject\":\"" + subject + "\"," +
                "\"product_code\":\"" + product_code + "\"}";          // 生成支付json数据
        System.out.println("支付生成json数据 bizContent=" + bizContent);
        // 提交支付请求
        alipayRequest.setBizContent(bizContent);
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        resultData.setData(form);
        payService.updatePayOrder(payInfo);
       return resultData;
    }

    /**
     * 支付成功回调
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/addpayOrder.do",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView addpayOrder(HttpServletRequest request,HttpServletResponse response) throws IOException, AlipayApiException {
        String APP_PRIVATE_KEY = Contants.APP_PRIVATE_KEY;
        //支付宝的公钥
        String ALIPAY_PUBLIC_KEY = Contants.ALIPAY_PUBLIC_KEY;
        System.out.println("支付成功, 进入同步通知接口...");
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("========================================"+params);
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2");
            ModelAndView mv = new ModelAndView("redirect:http://172.16.10.137:8081/#/userHome/userdingdan");
        if (signVerified) {
            PayInfo payInfo= new PayInfo();
            payInfo.setOrderNumber(params.get("out_trade_no"));
            payInfo.setUserPayble("total_amount");
            if (payInfo !=null){
                payService.updateSuceessPayOrder(payInfo);
                mv.addObject("code",Contants.SUCCESS);
                mv.addObject("msg","支付成功");
            }else {
                mv.addObject("code",Contants.FAILURE);
                mv.addObject("msg","系统异常");
            }
            }else {
            mv.addObject("code",Contants.FAILURE);
            mv.addObject("msg","您还没支付");
        }
        return mv;
    }

    @RequestMapping(value = "/agreeExitPayOrder.do",method = RequestMethod.POST)
    @ApiOperation(value = "同意退款接口",notes = "同意退款接口",httpMethod = "post",response = ResultData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="退款成功"),
            @ApiResponse(code=500,message="后台服务错误")
    })

    @ResponseBody
    public ResultData agreeExitPayOrder(@RequestBody PayInfo payInfo){
        System.out.println("====================="+ payInfo.getUserPayble());
        ResultData resultData=new ResultData();
        String URL = "https://openapi.alipaydev.com/gateway.do";
        // 生产环境支付地址为https://openapi.alipay.com/gateway.do
        // 创建的应用ID
        String APP_ID = "2016103000779855";
        String returnStr = null;
        try {
            /**  支付宝退款接口
             * @param out_trade_no 订单支付时传入的商户订单号,不能和支付宝交易号（trade_no）同时为空。
             * @param trade_no 支付宝交易号
             * @param refund_amount 需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
             * @return 将提示信息返回
             */
            //自己的私钥
            String APP_PRIVATE_KEY = Contants.APP_PRIVATE_KEY;
            //支付宝的公钥
            String ALIPAY_PUBLIC_KEY = Contants.ALIPAY_PUBLIC_KEY;
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, "json", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
           // AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); //  创建API对应的request
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + payInfo.getOrderNumber() + "\"," +
                    "\"refund_amount\":\"" + payInfo.getUserPayble()+ "\"," +
                    "\"refund_reason\":\"正常退款\"" +
                    " }");
            AlipayTradeRefundResponse response;
            response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("支付宝退款成功");
                //退款成功后修改订单状态
                resultData= payService.updateRefund(payInfo);
            } else {
                //失败会返回错误信息
                returnStr = response.getSubMsg();
                resultData.setMsg(returnStr);
                resultData.setCode(Contants.FAILURE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultData;
    }

    @ResponseBody
    @RequestMapping(value = "/noAgreeExitPayOrder.do",method = RequestMethod.POST)
    @ApiOperation(value = "驳回退款接口",notes = "驳回退款接口",httpMethod = "post",response = ResultData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="驳回成功"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    public ResultData noAgreeExitPayOrder(@RequestBody Refund  refund){
        ResultData resultData = payService.noAgreeExitPayOrder(refund);
        return resultData;
    }
    @ResponseBody
    @RequestMapping(value = "/queryRefundOrder.do",method = RequestMethod.GET)
    @ApiOperation(value = "查询所有退款订单以及通过订单状态条件查询",notes = "查询所有退款订单以及通过订单状态条件查询接口",httpMethod = "post",response = ResultData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="查询所有退款订单"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    @ApiImplicitParam(name = "orderStart",value = "通过订单状态条件查询",dataType = "int",paramType = "query")
    public ResultData queryRefundOrder(Integer orderStart){
        ResultData resultData =payService.queryRefundOrder(orderStart);
        return resultData;
    }
    @ResponseBody
    @RequestMapping(value = "/applyRefundByOrder.do",method = RequestMethod.POST)
    @ApiOperation(value = "用户申请退款",notes = "用户申请退款接口",httpMethod = "post",response = ResultData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="申请成功"),
            @ApiResponse(code=500,message="后台服务错误")
    })
    public ResultData addApplyRefundByOrder(@RequestBody Refund refund){
        ResultData resultData =payService.addApplyRefundByOrder(refund);
        return resultData;
    }
}
